//index.js
//获取应用实例
var app = getApp();

Page({
    data: {
     
        from_uid: 0,
        showPulldown: false,
        isFixed: false,
        isshow_subsidy: true,
        minprice: '',
        maxprice: '',
        showMotal:false,

        showMotal:false,
        motalBox2:false,
        isShare:'',

        maxprice: '',
        motalShow1: false,
       motalShow2:false,

        sort: 0,
        cname: "",
        sortName: "默认",
        currentTab: 0,
        currentTab2: 0,
        hiddenLoading: false,
        indicatorDots: true,
        autoplay: true,
        interval: 3000,
        from_uid: 0,
        nickname: '',
        memberid: 0,
        datalock: false,
        uri: "list",
        searchkey: "",
        showAnimation: false,
        globalset: {

        },
        homeskinid: -1,
        duration: 100,
        "banner": [
        ],
        commodity: [

        ],
        canShowCuttingDetail:false

       
    },

    onLoad: function (options) {
        var $that = this;
        var memberinfo = wx.getStorageSync('memberinfo');
       
        var memberid_fomid='';

        if (options.from_uid){
            memberid_fomid = options.from_uid;
            $that.setData({ memberid_fomid: options.from_uid});
        }else{
            memberid_fomid = memberinfo.memberid;
            $that.setData({ memberid_fomid: memberinfo.memberid });
        }
    
    
        var that = this;
        if (typeof options.from_uid != "undefined") {
            wx.setStorage({
                key: "from_uid",
                data: options.from_uid
            });
            this.setData({
                from_uid: options.from_uid,
                datalock: false
            });
        } else {
            /*
            this.setData({
              from_uid: 1,
              datalock: false
            });
            */
        }
        if (typeof options.skuId != "undefined" ) {

            this.setData({
                skuId: options.skuId
            });
        } else {
            // this.setData({
            //   skuId: 16113788870
            // });
        }
        //获取cuttingid
        $that.getMyCuttingDetail_1();
        //进入页面执行一次自己为自己砍价
        
       


        //app.setTabBar();

        this.getGlobalSet();
        //控制弹窗的函数
        //调用应用实例的方法获取全局数据
        app.getUserInfo(function (userInfo) {
            //更新数据
            $that.setData({
                userInfo: userInfo
            })
        })
    

    },
    initIndex: function () {
        var $this = this;
        $this.goodList(1);
        //执行砍价明细函数
      //  $this.ajaxGetMyCuttingDetail();
        //$this.goodList(1, "limittime", '', 0);
        //$this.goodList(1, "realtime", '', 0);

        var memberinfo = wx.getStorageSync('memberinfo');
        //砍价按钮内容赋值

        //if (memberinfo.)
        $this.setData({ memberinfo: memberinfo });
        var globalset = wx.getStorageSync('globalset');
        $this.setData({
            commission: 0,
            datalock: false
        });
        //计算总的佣金比例
        var total_commission = 0;
        if (globalset.memberlevel != undefined && globalset.memberlevel.length != undefined) {
            for (var i = 0; i < globalset.memberlevel.length; i++) {
             
                //当前会员类型的等级佣金比例
                if (globalset.memberlevel[i].type == memberinfo.type && globalset.memberlevel[i].name == memberinfo.level) {
                    total_commission = parseFloat(globalset.memberlevel[i].myteam_credit2) + parseFloat(globalset.memberlevel[i].myleader1_credit2) + parseFloat(globalset.memberlevel[i].myleader2_credit2);
                    //换成只取1级佣金的比例
                    total_commission = parseFloat(globalset.memberlevel[i].myteam_credit2);
                   
                    $this.setData({
                        commission: total_commission,
                        datalock: false
                    });
                 
                }
            }
        }
        if (memberinfo.type == 0) {
            if (globalset.isopen_subsidy == 0) {
                $this.setData({
                    isshow_subsidy: false
                });
            }
          
            total_commission = parseFloat(globalset.subsidy);
            $this.setData({
                commission: total_commission,
                datalock: false
            });
        }

        if (globalset.isshow_subsidy == 0) {
            $this.setData({
                isshow_subsidy: false
            });
        }
    },
    getGlobalSet: function () {
        var $this = this;
        app.util.request({
            url: 'entry/wxapp/Global',
            showLoading: false,
            data: {
                "m": 'nets_haojk'
            },
            method: 'post',
            success: function (response) {
                var globalset = response.data.data;
                $this.setData({
                    hiddenLoading: true
                });
                $this.setData({
                    globalset: globalset,
                    homeskinid: globalset.homeskinid
                });
                wx.setStorage({
                    key: "globalset",
                    data: globalset
                });
                //banner
                var banner_str = globalset.banner;
                var banner_json = JSON.parse(banner_str);
                if (banner_json != undefined && banner_json.list != null && banner_json.list != undefined && typeof banner_json.list != undefined && banner_json.list != null && banner_json.list != '') {
                    $this.setData({
                        banner: banner_json.list,
                        datalock: false
                    });
                }
                //图标菜单
                var newhead_menu_json = [];
                var head_menu_str = globalset.head_menu;
                var head_menu_json = JSON.parse(head_menu_str);
              

                if (head_menu_json != undefined && head_menu_json.list != null && head_menu_json.list != undefined && typeof head_menu_json.list != undefined && head_menu_json.list != null && head_menu_json.list != '') {
                    var menulen = head_menu_json.list.length;
                    for (var i = 0; i < 8; i++) {
                        newhead_menu_json.push(head_menu_json.list[i])
                    }


                    $this.setData({
                        imgmenu: newhead_menu_json,
                        datalock: false

                    });


                    var imgmenu2 = new Array();
                    for (var i = 8; i < 16; i++) {
                        imgmenu2.push(head_menu_json.list[i]);
                    }
                    $this.setData({
                        imgmenu2: imgmenu2,
                        datalock: false
                    });

                    $this.setData({
                        imgmenuAll: head_menu_json.list,
                        datalock: false
                    });


                    var imgmenu22 = new Array();
                    for (var i = 16; i < menulen; i++) {
                        imgmenu22.push(head_menu_json.list[i]);
                    }
                    $this.setData({
                        imgmenu22: imgmenu22,
                        datalock: false
                    });
                    var imgmenu222 = new Array();
                    for (var i = 24; i < menulen; i++) {
                        imgmenu222.push(head_menu_json.list[i]);
                    }
                    $this.setData({
                        imgmenu222: imgmenu222,
                        datalock: false
                    });
                }
               
                $this.getMember();

            }
        });

    },
    getMember: function () {
        var that = this;
        app.getUserInfo(function (userInfo) {
            //更新数据
            app.util.getUserInfo(function (response) {

                response.memberInfo.nickname = userInfo.nickName;
                response.memberInfo.avatar = userInfo.avatarUrl;
                response.memberInfo.city = userInfo.city;
                response.memberInfo.country = userInfo.country;
                response.memberInfo.province = userInfo.province;
                response.memberInfo.gender = userInfo.gender;
                that.addMember(response.memberInfo);
            });
        });
        // 页面渲染完成
    },
    
    addMember: function (userInfo) {
        var $this = this;
        app.util.request({
            url: 'entry/wxapp/AddMember',
            showLoading: false,
            data: {
                "m": 'nets_haojk',
                "from_uid": this.data.from_uid,
                "nickname": userInfo.nickname,
                "avatar": userInfo.avatar,
                "city": userInfo.city,
                "country": userInfo.country,
                "province": userInfo.province,
                "gender": userInfo.gender,
            },
            method: 'post',
            success: function (response) {
                //首页存储会员对象到缓存，其他页面直接读取缓存即可
                wx.setStorage({
                    key: "memberinfo",
                    data: response.data.data
                });
                $this.setData({
                    memberid: response.data.data.memberid,
                    nickname: response.data.data.nickname,
                    datalock: false
                });
               
                $this.initIndex();
            }
        });
    },
   
   
    bindChange: function (e) {
        var that = this;
        that.setData({ currentTab: e.detail.current });

    },

    onShareAppMessage: function (res) {
     
        var memberinfo = wx.getStorageSync("memberinfo");
        var $that=this;
     
        return {
            title:'帮我一起砍价，免费拿心仪好货吧' ,
            // path: '/haojk/pages/index/index?from_uid=' + memberinfo.memberid + '&from_nickname=' + memberinfo.nickname + '&type=' + memberinfo.type + '&homeskinid=' + memberinfo.homeskinid,

            path: '/haojk/pages/shareFreeOrderDetail/index?skuId=' + this.data.skuId + '&from_uid=' + $that.data.memberid_fomid,
            success: function (res) {
                // 转发成功
            },
            fail: function (res) {
                // 转发失败
            }
        }

    },
   
    goodList: function (page, t, callback, goodstype) {
        var $this = this;
        var limittime = 1;
        var realtime = 1;
        if (t == "limittime") {
            realtime = "";
        } else if (t == "realtime") {
            limittime = "";
        } else {
            //  $this.setData({canBottomRefresh:true});
            limittime = "";
            realtime = "";
        }
        if ($this.data.datalock) {
            //return false;
        }
        $this.setData({
            page: page,
            datalock: true,
        });

        app.util.request({
            url: 'entry/wxapp/GetFreeGoods',
            showLoading: false,
            data: {
                m: 'nets_haojk',
                page: page,
               
            },
            method: 'post',
            success: function (response) {
                if (typeof callback == 'function') {
                    callback(response.data.data);


                    $this.setData({
                        datalock: false
                    });
                } else {
                   
                    var goods = response.data.data;

                    $this.setData({
                        commodity: goods,
                        datalock: false
                    });
                  

                }
            }
        });
    },

    //事件处理函数
    skiptodetail: function (e) {
        var $that = this;

        var skuId = e.currentTarget.dataset.skuid;
        for (var i = 0; i < this.data.commodity.length; i++) {
            if (this.data.commodity[i].skuId == skuId) {
                var good = this.data.commodity[i];
                wx.setStorage({
                    key: "good",
                    data: good
                });
            }
        }


        //加入我的免单
        app.util.request({
            url: 'entry/wxapp/SetFreeGoodsDetail',
            data: {
                m: "nets_haojk",
                skuId: skuId,
                memberid: $that.data.memberinfo.memberid
            },
            method: 'post',
            success: function (response) {
              
                if (response.data.errno == 0) {
                    $that.getMyFreeGoods();

                    wx.navigateTo({
                        url: '../shareFreeOrderDetail/index?skuId=' + skuId
                    })
                }

            }
        })


    },
    onReachBottom: function () {

    },
   
    callFriendkanjia:function(e){
        var $that = this;

        if ($that.data.kanjiaType==4){
            $that.alsoWant();
        }else{
            if ($that.data.kanjiaType == 2) {
                $that.setData({ isShare: "" });

                $that.helpCutting();




            } else if ($that.data.kanjiaType == 1) {
               
                $that.setData({ isShare: "share" });
                // $that.onShareAppMessage();
            } else if ($that.data.kanjiaType == 3) {
               
               
                $that.setData({ isShare: "contact" });


            }
        }
        
       
       
    },
    //我也要免费拿
    alsoWant:function(){
        wx.redirectTo({
            url: '../shareFreeOrder/index'
        })
    },

    helpCutting:function(){
        var $that = this;
        var memberinfo = wx.getStorageSync('memberinfo');

        app.util.request({
            url: 'entry/wxapp/HelpCutting',
            showLoading: false,
            data: {
                m: 'nets_haojk',
                cuttingid: $that.data.cuttingid,
                memberid: memberinfo.memberid,

            },
            method: 'post',
            success: function (response) {
            
                if (response.data) {
                    $that.setData({ helpCuttingNum: response.data.data });
                    if (response.data.data == -1 && $that.data.kanjiaType==2){
                        wx.showModal({
                            title: '提示',
                            content: '你当天的砍价次数已用完',
                            success: function (res) {
                                if (res.confirm) {
                                   
                                } else if (res.cancel) {
                                  
                                }
                            }
                        })
                    } else if (response.data.data == -2 && $that.data.goodscuttingmemberid != memberinfo.memberid) {
                        wx.showModal({
                            title: '提示',
                            content: '你已经砍过此商品',
                            success: function (res) {
                                if (res.confirm) {
                                   
                                } else if (res.cancel) {
                                   
                                }
                            }
                        })
                    }else{
                        $that.setData({canShowCuttingDetail:true});
                        $that.getMyCuttingDetail();
                    }


                
                   
                }
                
                
            }
        })
    },
    getMyCuttingDetail:function(){
        var $that = this;
        if ($that.data.skuId != 0) {

            var memberinfo = wx.getStorageSync('memberinfo');

            app.util.request({
                url: 'entry/wxapp/GetMyCuttingDetail',
                data: {
                    m: "nets_haojk",
                    skuId: $that.data.skuId,
                    memberid:$that.data.memberid_fomid,
                    loginmemberid: memberinfo.memberid
                },
                method: 'post',
                success: function (response) {
                 
                  
                    var obj = response.data.data;
                    $that.setData({
                        showLoading: false,
                        good: response.data.data.goods,
                        cuttinglist: obj.cuttinglist,
                        cuttingid: response.data.data.id,
                      
                        goodsNickname: response.data.data.nickname,
                        cuttingprice: obj.cuttingprice,
                        wlPrice_after: obj.wlPrice_after,
                        goodsCuttingNickname: obj.nickname,
                        goodsCuttingAvatar: obj.avatar,
                        lessMoney: (obj.wlPrice_after - obj.cuttingprice).toFixed(2),

                    });
                  
                    //执行砍价
                   // $that.helpCutting()
                    //判断是否为自己砍价还是替朋友砍价
                  

                  
                    //赋值detail接口返回的id
                    $that.setData({ goodscuttingmemberid: response.data.data.memberid });
                    if (response.data.data.memberid == memberinfo.memberid) {
                        $that.setData({ kanjiaTypeText: '喊好友砍一刀', kanjiaType: 1 });
                    } else {
                        $that.setData({ kanjiaTypeText: '帮好友砍一刀', kanjiaType: 2 });
                    }
                    if ($that.data.lessMoney == 0 && response.data.data.memberid == memberinfo.memberid  ){
                        $that.setData({ kanjiaTypeText: '立即购买', kanjiaType: 3 });
                    }
                    // //判断帮别人砍价按钮显示
                    if (response.data.data.memberid != memberinfo.memberid && !response.data.data.iscutting) {
                    
                        $that.setData({ kanjiaTypeText: '我也要免费拿', kanjiaType: 4 });
                    }
                   
            
                    
                    //判断是否弹出帮好友砍价细节
                    if ($that.data.canShowCuttingDetail && $that.data.kanjiaType==2){
                    
                        if ($that.data.showMotal) {
                            $that.setData({
                                showMotal: false,

                            });

                        } else {
                            $that.setData({ showMotal: true })

                            $that.setData({
                                motalShow1: false,
                                motalShow2: true,
                            });

                        }
                    }

                  


                    //倒计时处理
                    var daojishi = parseInt(obj.createtime) ;
                 
                    var timestamp = Date.parse(new Date()) / 1000;
                   
                    daojishi = daojishi - timestamp;
                   
                    //倒计时函数
                    function countTime() {
                        var leftTime = daojishi;
                        var d, h, m, s;
                        if (leftTime >= 0) {
                            d = Math.floor(leftTime / 60 / 60 / 24);
                            h = Math.floor(leftTime / 60 / 60 % 24);
                            m = Math.floor(leftTime / 60 % 60);
                            s = Math.floor(leftTime % 60);
                        };
                        $that.setData({
                            hh: h, mm: m, dd: d, ss: s,
                        })
                        //  var timer = hh + mm + ss;
                        daojishi = daojishi - 1;
                    }
                    setInterval(countTime, 1000);
                }
            })
        } else {
            // wx.getStorage({
            //     key: 'good',
            //     success: function (res) {
            //         that.setData({ good: res.data });
            //     }
            // });
        }
    },
    getMyCuttingDetail_1: function () {
        var $that = this;
        if ($that.data.skuId != 0) {

            var memberinfo = wx.getStorageSync('memberinfo');

            app.util.request({
                url: 'entry/wxapp/GetMyCuttingDetail',
                data: {
                    m: "nets_haojk",
                    skuId: $that.data.skuId,
                    memberid: $that.data.memberid_fomid,
                    loginmemberid: memberinfo.memberid,
                },
                method: 'post',
                success: function (response) {
                    //console.log(response);
                   
           
                    var obj = response.data.data;
                    //console.log(obj);
                    console.log(obj.goodjson);
                    var goodjsonObj = JSON.parse(JSON.parse(obj.goodjson).goodjson);
                    console.log(goodjsonObj);
                    $that.setData({
                        showLoading: false,
                        good: response.data.data.goods,
                        cuttinglist: obj.cuttinglist,
                        cuttingid: response.data.data.id,
                        goodsNickname: response.data.data.nickname,
                        loginmemberid: memberinfo.memberid,
                       
                        cuttingprice: obj.cuttingprice,
                        wlPrice_after: obj.wlPrice_after,
                        goodsCuttingNickname :obj.nickname,
                        goodsCuttingAvatar: obj.avatar,
                        lessMoney: (obj.wlPrice_after - obj.cuttingprice).toFixed(2),

                    });
                    //执行购买前的读取接口
                    app.util.request({
                        url: 'entry/wxapp/Unionurl',
                        data: {
                            m: 'nets_haojk',
                            from_uid: $that.data.from_uid,
                            skuid: goodjsonObj.skuId,
                            couponUrl: goodjsonObj.couponList
                        },
                        method: 'post',
                        success: function (response) {

                            if (response.data.data == null) {
                                wx.showToast({
                                    title: '购买链接生成错误',
                                    icon: 'loading',
                                    duration: 2000
                                });
                            } else {
                                $that.setData({
                                    buyurl: response.data.data.data
                                });
                                goodjsonObj.buyurl = response.data.data.data;
                                goodjsonObj.m="nets_haojk";
                                app.util.request({
                                    
                                    url: 'entry/wxapp/Savecache',
                                    data: goodjsonObj,
                                    method: 'post',
                                    success: function (response) {

                                        $that.setData({
                                            showLoading: false
                                        });
                                    }
                                });

                            }
                        }
                    });
                 
                  
                  
                    //判断是否为自己砍价还是替朋友砍价
                   
                    //赋值detail接口返回的id
                    $that.setData({goodscuttingmemberid :response.data.data.memberid})
                    
                    
                    if (response.data.data.memberid == memberinfo.memberid) {
                        $that.setData({ kanjiaTypeText: '喊好友砍一刀', kanjiaType: 1 });
                    } else {
                        $that.setData({ kanjiaTypeText: '帮好友砍一刀', kanjiaType: 2 });
                    }
                    if ($that.data.lessMoney == 0 && response.data.data.memberid == memberinfo.memberid) {
                        $that.setData({ kanjiaTypeText: '立即购买', kanjiaType: 3 });
                    }

                    //判断帮别人砍价按钮显示
                    //判断帮别人砍价按钮显示
                    if (response.data.data.memberid != memberinfo.memberid && !response.data.data.iscutting) {
                   
                        $that.setData({ kanjiaTypeText: '我也要免费拿', kanjiaType: 4 });
                    }
                 
                    //新用户进来如果砍价还差0元  ,则改变按钮的状态
                    if ($that.data.lessMoney == 0 && response.data.data.memberid != memberinfo.memberid) {
                        $that.setData({ kanjiaTypeText: '我也要免费拿', kanjiaType: 4 });
                    }

                    // if (response.data.data.memberid != memberinfo.memberid && !response.data.data.iscutting) {
                    //     $that.setData({ kanjiaTypeText: '我也要免费拿', kanjiaType: 4 });
                    // }
                    //执行函数
               
                    if ($that.data.kanjiaType==1){
                        $that.helpCutting()
                    }
                  
                    
                    var daojishi = parseInt(obj.createtime)+1*24*60*60 ;
                  
                    var timestamp = Date.parse(new Date()) / 1000;
               
                    daojishi = daojishi - timestamp;
              
                    //倒计时函数
                    function countTime() {
                        var leftTime = daojishi;
                        var d, h, m, s;
                        if (leftTime >= 0) {
                            d = Math.floor(leftTime / 60 / 60 / 24);
                            h = Math.floor(leftTime / 60 / 60 % 24);
                            m = Math.floor(leftTime / 60 % 60);
                            s = Math.floor(leftTime % 60);
                        }else {
                            d = '00';
                            h = '00';
                            m = '00';
                            s = '00';
                        };
                        $that.setData({
                            hh: h, mm: m, dd: d, ss: s,
                        })
                        //  var timer = hh + mm + ss;
                        daojishi = daojishi - 1;
                    }
                    setInterval(countTime, 1000);
                }
            })
        } else {
            // wx.getStorage({
            //     key: 'good',
            //     success: function (res) {
            //         that.setData({ good: res.data });
            //     }
            // });
        }
    },
    getMyFreeGoods: function () {
        var $that = this;
        //加入我的免单
        app.util.request({
            url: 'entry/wxapp/SetFreeGoodsDetail',
            data: {
                m: "nets_haojk",
                skuId: 0,
                memberid: $that.data.memberinfo.memberid
            },
            method: 'post',
            success: function (response) {
                var obj = response.data.data;

              
                if (response.data.errno == 0) {
                    //$that.setData({ myFreeGoods: response.data.data});
                }
                $that.setData({
                    importordersArray: obj,
                });


                setInterval(function () {
                    for (var i = 0; i < obj.length; i++) {
                        //obj[i].createtime = countTime(obj[i].createtime);
                        obj[i].showdaojishi = countTime(obj[i].createtime);
                    }
                }, 1000)





                //倒计时函数
                function countTime(a) {
                    var daojishi = parseInt(a);
                 

                    var timestamp = Date.parse(new Date()) / 1000;
                  
                    daojishi = daojishi - timestamp;
                    var leftTime = daojishi + 70000;
                    
                    var d, h, m, s;
                    if (leftTime >= 0) {
                        d = Math.floor(leftTime / 60 / 60 / 24);
                        h = Math.floor(leftTime / 60 / 60 % 24);
                        m = Math.floor(leftTime / 60 % 60);
                        s = Math.floor(leftTime % 60);
                    };
               
                    $that.setData({ myFreeGoods: obj })
                    return d + ':' + h + ':' + m + ':' + s
                    //  var timer = hh + mm + ss;
                    daojishi = daojishi - 1;

                }
                // setTimeout(countTime, 3000);













            }
        })
    },

})
